package com.gengzp.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.gengzp.common.exception.BusinessException;

import java.util.List;
import java.util.Map;

/**
 * @ClassName JsonUtils
 * @Description json数据转换工具类
 * @Author gengzp
 * @Date 2025/5/31 17:01
 */
public class JsonUtils {

    private final static ObjectMapper objectMapper = initObjectMapper();

    private static ObjectMapper initObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 忽略未知字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 忽略空对象序列化异常
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 支持 Java 8 时间 API（LocalDateTime 等）
        objectMapper.registerModule(new JavaTimeModule());
        return objectMapper;
    }

    private JsonUtils() {
    }

    /**
     * 将对象转换成 JSON 字符串
     */
    public static String toJsonString(Object obj) {
        if (obj == null) return null;
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw BusinessException.get(String.format("JSON 序列化失败: %s", e.getMessage()));
        }
    }

    /**
     * 将 JSON 字符串解析为对象
     */
    public static <T> T parseObject(String json, Class<T> clazz) {
        if (json == null || json.isBlank()) return null;
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw BusinessException.get(String.format("JSON 反序列化失败: %s", e.getMessage()));
        }
    }

    /**
     * 将 JSON 字符串解析为泛型对象（如 List<T>, Map<String, T> 等）
     */
    public static <T> T parseObject(String json, TypeReference<T> typeReference) {
        if (json == null || json.isEmpty()) return null;
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            throw BusinessException.get(String.format("JSON 泛型反序列化失败: %s", e.getMessage()));
        }
    }

    /**
     * 将 JSON 字符串解析为 Map<String, Object>
     */
    public static Map<String, Object> parseMap(String json) {
        return parseObject(json, new TypeReference<>() {
        });
    }

    /**
     * 将 JSON 字符串解析为 List<Map<String,, Object>>
     */
    public static List<Map<String, Object>> parseListMap(String json) {
        return parseObject(json, new TypeReference<>() {
        });
    }

}
